#include "stdafx.h"
#include "ckMatrixD.h"
#include "math.h"

namespace ck
{
	namespace data
	{
		MatrixD::MatrixD()
		{
			m_data = NULL;
		}


		MatrixD::~MatrixD()
		{
			if (m_data)
			{
				delete[] m_data;
				m_data = NULL;
			}
		}

		double* MatrixD::GetData()
		{
			return m_data;
		}

		double* MatrixD::GetDataPtr(z_uint32 i, z_uint32 j)
		{
			return (m_data + i * m_width + j);
		}

		double MatrixD::GetValue(z_uint32 i, z_uint32 j)
		{
			return *(m_data + i * m_width + j);
		}

		RESULTCODE MatrixD::Standardize()
		{
			double sum = Sum();
			double* ptr = m_data;

			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					*ptr = *ptr / sum;
				}
			}
			
			return RC_SUCCESS;
		}

		double MatrixD::Sum()
		{
			double sum = 0.0;
			double* ptr = m_data;

			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					sum += *ptr;
				}
			}

			return sum;
		}

		double MatrixD::GetMeanX()
		{
			double v = 0.0f;

			double* ptr = m_data;
			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					v += j * (*ptr);
				}
			}
			return v;
		}

		double MatrixD::GetMeanY()
		{
			double v = 0.0f;

			double* ptr = m_data;
			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					v += i * (*ptr);
				}
			}
			return v;
		}

		double MatrixD::GetVarianceX()
		{
			double mx = GetMeanX();
			double sum = 0.0f;

			double* ptr = m_data;
			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					sum += pow((j-mx),2) * (*ptr);
				}
			}

			return sqrt(sum);
		}

		double MatrixD::GetVarianceY()
		{
			double my = GetMeanY();
			double sum = 0.0f;

			double* ptr = m_data;
			for (z_uint32 i = 0; i < m_height; i++)
			{
				for (z_uint32 j = 0; j < m_width; j++, ptr++)
				{
					sum += pow((i - my), 2) * (*ptr);
				}
			}

			return sqrt(sum);
		}
	}
}
